package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        // 前端的数据
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在,抛出业务异常
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 思路：把前端的密码，用MD5加密，然后和数据库的密码比对
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("Dd5Password:{}",md5Password);
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        // 调用emp mapper保持员工
        // 写数据库之前，准备数据，准备完之后写数据库
        // 员工表需要插入11个数据，前端传5个数据，我们需要准备6个
        log.info("[当前线程]，thread:{}",Thread.currentThread().getId());
        Integer status = 1;
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();
        // 创建人和更新人的ID（当前登录用户的ID），从token中获取
        // todo 稍后处理如何从token中获取ID，默认是1
        Long empId = BaseContext.getCurrentId();
        String username = BaseContext.threadLocalEmpUserName.get();
        log.info("[当前线程]，thread:{} empId:{},empUsername:{}",Thread.currentThread().getId(),empId,username);
        Long createUser = empId;
        Long updateUser = empId;
        // 把前端数据和准备的数据封装成功 实体类对象
        Employee employee = new Employee();
        employee.setName(employeeDTO.getName());
        employee.setUsername(employeeDTO.getUsername());
        employee.setIdNumber(employeeDTO.getIdNumber());
        employee.setSex(employeeDTO.getSex());
        employee.setPhone(employeeDTO.getPhone());
        employee.setStatus(status);

         // 如果使用了AOP，让AOP的切面帮助我们给实体类的这4个字段赋值
        // 实体类传递给Mapper对象的方法，结论AOP的切入点mapper
//        employee.setCreateTime(createTime);
//        employee.setUpdateTime(updateTime);
//        employee.setCreateUser(createUser);
//        employee.setUpdateUser(updateUser);

        // 默认密码是123456
        String md5Password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(md5Password);
        // 调用mapper
        log.info("emp:{}",employee);
        // 思路：使用AOP，创建一个切面，切面的切入点拦截是Service的方法还是Mapper的方法
        // 我们目的是就是在写数据库之前，不用自己给功能字段填充数据
        employeeMapper.insertEmp(employee);


    }

    @Override
    public PageResult findByPage(EmployeePageQueryDTO pageQueryDTO) {
        // 调用mapper
        // 使用分页插件,把当前页面和每页条数告诉分页插件
        // 分页插件帮我们动态分页，计算记录数和结果集
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Page<Employee> employeePage = employeeMapper.selectByPageAndName(pageQueryDTO.getName());
        // 从返回的结果中，获取总记录数和分页结果集
        PageResult pageResult = new PageResult(employeePage.getTotal(),employeePage.getResult());
        return pageResult;
    }

    @Override
    public void setEmpStatus(Integer status, Integer id) {
        // 调用mapper
        Employee employee = Employee.builder()
                .id((long)id)
                .status(status)
                .build();
        employeeMapper.updateEmp(employee);
    }

    @Override
    public Employee findById(Long id) {
        //调用mapper
        Employee employee = employeeMapper.selectById(id);
        // 把密码替换 ******
        employee.setPassword("******");
        return employee;
    }

    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        // 调用mapper
        // 更新前，准备数据
        Employee employee = new Employee();
        // 把DTO复制给实体类对象
        BeanUtils.copyProperties(employeeDTO,employee);
        // 设置更新时间和更新人
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(employee);
    }

}



















